//
//  SDGameController.m
//  Sudoku
//
//  Created by wxlan on 16/6/13.
//  Copyright © 2016年 wxlan. All rights reserved.
//

#import "SDGameController.h"
#import "SDCheckButton.h"
#import "SDChooseGameController.h"

#define numCount 81
#define rowCount 9

#define kGameDataPath  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"gameData.data"]

@interface SDGameController ()<UIAlertViewDelegate, SDCheckButtonDeletage>
@property (nonatomic, strong) NSMutableArray *numberArray;
@property (nonatomic, strong) SDCheckButton *selectedButton; // 记录当前选中的button

@property (nonatomic, weak) UIView *gameView;
@property (nonatomic, strong) NSMutableArray *unFillCheckArray; // 未填充的各自
@property (nonatomic, strong) NSMutableArray *gameDataArray; // 游戏数据

@property (nonatomic, weak) UIView *coverView1; // 点击变色
@property (nonatomic, weak) UIView *coverView2;
@property (nonatomic , weak) UILabel *coverLabel;
@property (nonatomic, strong) NSMutableArray *smallCoverArray;


@property (nonatomic, assign) BOOL isEdit; // 是否是标记模式
@property (nonatomic, weak)   MZTimerLabel *timeLabel;
@property (nonatomic, weak)   UILabel *titleLabel;

@property (nonatomic, weak) UIButton *limitButton;// 穷尽按钮

@property (nonatomic, assign) BOOL isShowOnlyNumber; // 是否直接天上唯一数字或备选数

@property (nonatomic, assign) NSInteger helpClickCount; // 提示按钮点击次数


//@property (nonatomic, strong) NSMutableArray *errorCheckArray; // 收集错误的格子
//@property (nonatomic, strong) NSMutableArray *sameRowColumnArray; // 同行同列格子
@end

@implementation SDGameController
- (NSMutableArray *)smallCoverArray
{
    if (_smallCoverArray == nil) {
        _smallCoverArray = [NSMutableArray array];
    }
    return _smallCoverArray;

}
- (NSMutableArray *)gameDataArray
{
    NSString *numString = self.levelDetailModel.lastNumber;
    if (numString.length < 81) {
        numString = self.levelDetailModel.originNumber;
    }
        _gameDataArray = [NSMutableArray array];
        [_gameDataArray removeAllObjects];
        NSInteger length = numString.length;
        for (int i = 0; i < length; i++) {
            char ch = [numString characterAtIndex:i];
            [_gameDataArray addObject:[NSString stringWithFormat:@"%c", ch]];
        }
    
    return _gameDataArray;
}


- (NSMutableArray *)numberArray
{
    if (_numberArray == nil) {
        _numberArray = [NSMutableArray array];
    }
    return _numberArray;
}
- (NSMutableArray *)unFillCheckArray
{
    if (_unFillCheckArray == nil) {
        _unFillCheckArray = [NSMutableArray array];
    }
    return _unFillCheckArray;
}

- (SDCheckButton *)selectedButton
{
    if (_selectedButton == nil) {
        _selectedButton = [[SDCheckButton alloc] init];
        
    }
    return _selectedButton;
}

- (instancetype)initWithLevelDetailModel:(SDLevelDetailModel *)levelDetailModel
{
    if (self = [super init]) {
        self.levelDetailModel = levelDetailModel;
    }
    return self;
}

- (void)setLevelDetailModel:(SDLevelDetailModel *)levelDetailModel
{
    _levelDetailModel = levelDetailModel;
    NSString *numString =levelDetailModel.originNumber;
    [self.numberArray removeAllObjects];
    NSInteger length = numString.length;
    for (int i = 0; i < length; i++) {
        char ch = [numString characterAtIndex:i];
        [self.numberArray addObject:[NSString stringWithFormat:@"%c", ch]];
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
       self.isEdit = [[NSUserDefaults standardUserDefaults] boolForKey:@"isEdit"];
    [self buildUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseOtherGame:) name:@"chooseOtherGameNotification" object:nil];
    if (self.levelDetailModel.playState == LevelPlayStateNotStart) {
        self.levelDetailModel.playState = LevelPlayStatePlaying;
    }
    [self initializePlayTime];
    
   NSArray *array = [self getSameRowIndex:0];
//    [self temp];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.levelDetailModel.playState != LevelPlayStateSolved)
    {
        [self initializePlayTime];
    }
//    [self.timeLabel addTimeCountedByTime:];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timeLabel pause];
    [self saveGameData];
    
}- (void)chooseOtherGame:(NSNotification *)notification
{
    
    NSArray *indexPath = notification.userInfo[@"userInfo"];
    [self chooseGameAtIndex:[NSIndexPath indexPathForRow:[indexPath[1] integerValue] inSection:[indexPath[0] integerValue]]];
    
}

- (void)chooseGameAtIndex:(NSIndexPath *)indexPath
{
    self.selectedButton = nil;
    [self saveGameData];

    [self.unFillCheckArray removeAllObjects];
    [self removeAllSmallCover];
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSString *levelStr;
    switch (section) {
        case 0:
            levelStr = @"初级题";
            break;
        case 1:
            levelStr = @"中级题";
            break;
        case 2:
            levelStr = @"高级级题";
            break;
            
            
            
        default:
            break;
    }
    self.titleLabel.text = [NSString stringWithFormat:@"Sudoku %@-%ld", levelStr,row + 1];
    self.levelDetailModel = [[SDGameManager sharedSDGameManager] getOneGameDataWithIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
    if (self.levelDetailModel.playState == LevelPlayStateNotStart) {
        self.levelDetailModel.playState = LevelPlayStatePlaying;
    }
    NSArray *path;
    if (indexPath.section == 0) {
        path = @[@(0),@(indexPath.row)];
    }else if (indexPath.section == 1 )
    {
        path = @[@(1),@(indexPath.row)];
        
    }else
    {
        path = @[@(2),@(indexPath.row)];
        
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:path forKey:@"lastGame"];

//    NSString *numString = self.levelDetailModel.originNumber;
//    [self.timeLabel reset];
    [self initializePlayTime];
    
    for (int i = 0; i < numCount; i++) {
        [self initializeGameViewDataAtIndex:i];
        
    }
    
    [self verificationConflict];

    [self verificationGameover];
    

    [self saveGameData];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)buildUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self buildTopView];
    [self buildGameView];
    [self buildKeyboardView];
    
}
- (void)buildTopView
{
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(@(64));
    }];
    UIButton *leftButton = [[UIButton alloc] init];
    [topView addSubview:leftButton];
    leftButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [leftButton setTitle:@"题库" forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(50));
        make.left.equalTo(topView).with.offset(10);
        make.top.bottom.equalTo(topView).with.offset(10);
    }];
    @weakify(self)
    leftButton.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self)
        [self presentViewController:[[SDChooseGameController alloc] init] animated:YES completion:nil];
        return [RACSignal empty];
    }];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    self.titleLabel = titleLabel;
    [topView addSubview:titleLabel];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    NSArray *indexPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastGame"];
    NSString *levelStr= @"";
    NSInteger section = [indexPath.firstObject integerValue];
    NSInteger row = [indexPath.lastObject integerValue];
    switch (section) {
        case 0:
            levelStr = @"初级题";
            break;
        case 1:
            levelStr = @"中级题";
            break;
        case 2:
            levelStr = @"高级级题";
            break;


            
        default:
            break;
    }
    titleLabel.text = [NSString stringWithFormat:@"Sudoku %@-%ld", levelStr,row + 1];
    titleLabel.textColor = [UIColor whiteColor];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(250));
        make.centerX.equalTo(topView);
        make.top.bottom.equalTo(topView).with.offset(10);
        
    }];
    MZTimerLabel *timeLabel = [[MZTimerLabel alloc] init];
    self.timeLabel = timeLabel;
    [topView addSubview:timeLabel];
    timeLabel.timeFormat = @"HH:mm:ss";
//    [timeLabel start];
//    timeLabel.text = @"00:00";
    timeLabel.textColor = [UIColor whiteColor];
    timeLabel.textAlignment = NSTextAlignmentRight;
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(100));
        make.top.bottom.equalTo(topView).offset(10);
        make.right.equalTo(topView).with.offset(-10);
    }];
}
- (void)buildGameView
{
    UIView *gameView = [[UIView alloc] init];
    self.gameView = gameView;
    gameView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:gameView];
    [gameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.equalTo(self.view.mas_width);
        make.top.equalTo(self.view).with.offset(64);
    }];
    for (int i = 0; i < numCount; i++) {

        [self creatGameViewCheckAtIndex:i];
        [self initializeGameViewDataAtIndex:i];

    }
    [self verificationConflict];
    [self verificationGameover];

}
//第一次创建gameView
- (void)creatGameViewCheckAtIndex:(NSInteger)index
{
    CGFloat margin = 2;
    CGFloat checkWidth = (self.view.width- 2 * margin)/rowCount;

    SDCheckButton *button = [[SDCheckButton alloc] initWithWidth:checkWidth];
    button.delegate = self;
    button.layer.borderWidth = 0.5;
    button.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [self.gameView addSubview:button];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    NSInteger row = index/rowCount;
    NSInteger column = index%rowCount;
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(checkWidth));
        make.left.equalTo(@(column * checkWidth + column/3 * margin) );
        make.height.equalTo(@(checkWidth));
        make.top.equalTo(@(row * checkWidth + row/3 * margin));
    }];
    @weakify(self)
    button.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [self.coverLabel removeFromSuperview];
        if (self.selectedButton != button) {
            self.helpClickCount = 0;
            self.selectedButton.selected = !self.selectedButton.selected;
            button.selected = !button.selected;
            self.selectedButton = button;
            
        }
        return [RACSignal empty];
    }];

}
// 初始化GameView数据
- (void)initializeGameViewDataAtIndex:(NSInteger)index
{
        SDCheckButton *button = self.gameView.subviews[index];
        [self hiddenLabelOfCheckButton:button];
        button.isOrigin = NO;
        button.selected = NO;
    button.clickCount = NO;
    button.isShowMakr = NO;
        button.userInteractionEnabled = YES;
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString *number = self.numberArray[index];
        CGFloat margin = 2;
        CGFloat checkWidth = (self.view.width- 2 * margin)/rowCount;
//    [button setTitle:number forState:UIControlStateNormal];
        if (![number isEqualToString:@"0"]) {
            [button setTitle:number forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor] size:CGSizeMake(checkWidth, checkWidth)] forState:UIControlStateNormal];
//
            button.isOrigin = YES;
            button.isFill = YES;
            
            
        }else
        {
//            [self.unFillCheckArray addObject:button];
            button.isOrigin = NO;
            NSString *number = self.numberArray[index];
            if (self.gameDataArray.count > 0) {
                number = self.gameDataArray[index];
            }
            
            if (number == nil || [number isEqualToString:@"0"]) {
                number = @" ";
                button.isFill = NO;
                if (![self.unFillCheckArray containsObject:button]) {
                    [self.unFillCheckArray addObject:button];
                }
            }
            if (number != nil && ![number isEqualToString:@"0" ] && ![number isEqualToString:@" "]) {
                button.isFill = YES;
                if ([self.unFillCheckArray containsObject:button]) {
                    [self.unFillCheckArray removeObject:button];
                }

            }
            [button setTitle:[NSString stringWithFormat:@"%@", number] forState:UIControlStateNormal];
//
            [button setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(checkWidth, checkWidth)] forState:UIControlStateNormal];
            
            
        }
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor yellowColor] size:CGSizeMake(checkWidth, checkWidth)] forState:UIControlStateSelected];
        
    
}
// 初始化时间
- (void)initializePlayTime
{
    NSString *lastTime = self.levelDetailModel.playTime;
    NSArray  *array= [lastTime componentsSeparatedByString:@":"];
    NSTimeInterval time;
    if (array.count == 3) {
        time = [array.firstObject integerValue]*3600 + [array[1] integerValue]*60 + [array[2] integerValue];
    }else if(array.count == 2)
    {
        time =  [array[0] integerValue]*60 + [array[1] integerValue];
    }else
    {
        time = 0;
    }
    [self.timeLabel reset];
    [self.timeLabel start];
    
    [self.timeLabel addTimeCountedByTime:time];
    if(self.levelDetailModel.playState == LevelPlayStateSolved)
    {
        [self.timeLabel pause];
    }

}
- (void)buildKeyboardView
{
    UIView *keyboardView = [[UIView alloc] init];
    keyboardView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:keyboardView];
    [keyboardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.gameView.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    
    NSInteger keyboardCount = 12;
    CGFloat keyboardMargin = 5;
    CGFloat keyboardWidth = (self.view.width- 7*keyboardMargin)/6;
    CGFloat keyboardHeight = (self.view.height- self.view.width - 64);
    CGFloat buttonHeight = (keyboardHeight - 4*keyboardMargin)/3;

    for (int i = 0; i < keyboardCount; i++) {
        UIButton *button = [[UIButton alloc] init];
        [keyboardView addSubview:button];
        NSInteger row = i/6;
        NSInteger column = i%6;
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor] size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateNormal];

        [button setBackgroundImage:[UIImage imageWithColor:[UIColor orangeColor] size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateHighlighted];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        if (column != 5 ) {
            if (row == 0) {
                [button setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
                
            }else
            {
                [button setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
                
            }
            if (row == 1 &&  column == 4) {
                [button setTitle:@"消除" forState:UIControlStateNormal];
                
            }
            
            @weakify(self)
                button.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
                    @strongify(self);
                    [self.coverLabel removeFromSuperview ];
                    [self removeAllSmallCover];
                    if (self.isEdit) {
                        if(self.selectedButton.isFill || self.selectedButton.isOrigin)
                        {
                            return [RACSignal empty];
                            
                        }
                        if (row == 1 && column == 4) { // 点击C键
                            self.selectedButton.isShowMakr = NO;
                            [self hiddenLabelOfCheckButton:self.selectedButton];
                        }else
                        {
                            UILabel *label = (UILabel *)[self.selectedButton viewWithTag:([button.currentTitle intValue])];
                            label.hidden = !label.hidden;
                            self.selectedButton.isShowMakr = YES;
                            
                        }

                    }else
                    {
                        if (row == 1 && column == 4) { // 点击C键
                            [self.selectedButton setTitle:@" " forState:UIControlStateNormal];
                            if (![self.unFillCheckArray containsObject:self.selectedButton]) {
                                [self.unFillCheckArray addObject:self.selectedButton];
                            }
                            self.selectedButton.isFill = NO;
                            
                        }else  // 点击数字键
                        {
                            [self.selectedButton setTitle:button.currentTitle forState:UIControlStateNormal];
                            self.selectedButton.isFill = YES;
                            if ([self.unFillCheckArray containsObject:self.selectedButton]) {
                                [self.unFillCheckArray removeObject:self.selectedButton];
                            }
//                            [self hiddenLabelOfCheckButton:self.selectedButton];

                        }
                        // 验证数字是否重复,如果重复就标红显示
                        [self verificationConflict];
                        // 验证游戏是否完成
                        [self verificationGameover];
                        [self saveGameData];

                    }
                    return [RACSignal empty];
                }];
            
        }else
        {
            if (row == 0) {
                button.selected = self.isEdit;
                [button setTitle:@"备选" forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageWithColor:mRGBToColor(0x98F5FF) size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateSelected];//                [button setTitle:@"Back" forState:UIControlStateSelected];
                @weakify(self)
                button.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
                    @strongify(self);
                    [self.coverLabel removeFromSuperview];
                    [self removeAllSmallCover];
                    button.selected = !button.selected;
                    self.isEdit = !self.isEdit;
                    [[NSUserDefaults standardUserDefaults] setBool:self.isEdit forKey:@"isEdit"];
                    return [RACSignal empty];
                }];
                
//                [self removeAllSmallCover];
            }else
            {
                [button setTitle:@"辅助" forState:UIControlStateNormal];
                button.selected = [[NSUserDefaults standardUserDefaults] boolForKey:@"isShowCrossView"];
                [button setBackgroundImage:[UIImage imageWithColor:mRGBToColor(0x98F5FF) size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateSelected];
                @weakify(self)
                button.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
                    @strongify(self);
                    button.selected = !button.selected;
                    [self.coverLabel removeFromSuperview];
                    [self removeAllSmallCover];
                    [[NSUserDefaults standardUserDefaults] setBool:button.selected forKey:@"isShowCrossView"];
////                    [self removeAllSmallCover];
//                    [self getAnswerOfCheckButton:self.selectedButton];
                    return [RACSignal empty];
                }];

                
            }
        }
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(keyboardWidth));
            make.height.equalTo(@(buttonHeight));
            make.left.equalTo(@(column * (keyboardWidth+ keyboardMargin) + keyboardMargin));
            make.top.mas_equalTo(keyboardMargin + (row) * (keyboardMargin + buttonHeight));
            
        }];
        
        
        
    }
    
    NSArray *buttonTitleArray = @[@"提示",@"帮助",@"<",@">"];
    for (int i = 0; i < 4 ; i++) {
        UIButton *button = [[UIButton alloc] init];
        [keyboardView addSubview:button];
        if (i == 1) {
            button.enabled = NO;
            self.limitButton = button;
            
        }
        [button setTitle:buttonTitleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor] size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateNormal];
        
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor orangeColor] size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateHighlighted];
        [self.limitButton setBackgroundImage:[UIImage imageWithColor:mRGBToColor(0x8c8c8c) size:CGSizeMake(keyboardWidth, buttonHeight)] forState:UIControlStateDisabled];


        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.equalTo(keyboardView);
            
            make.width.mas_equalTo(keyboardWidth);
            make.height.mas_equalTo(buttonHeight);
            make.bottom.equalTo(keyboardView).with.offset(-keyboardMargin);
            if(i>=2)
            {
                make.left.equalTo(@((i + 2) * (keyboardWidth+ keyboardMargin) + keyboardMargin));
            }else
            {
                make.left.equalTo(@((i ) * (keyboardWidth+ keyboardMargin) + keyboardMargin));
 
            }

            
        }];

        @weakify(self)
        

        button.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @strongify(self);
            
            NSArray *lastGamePath = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastGame"];
            NSInteger lastGameSection = [lastGamePath.firstObject integerValue];
            NSInteger lastGameRow = [lastGamePath.lastObject integerValue];
            NSInteger  askCount = [[SDGameManager sharedSDGameManager] numberOfAskAtSection:lastGameSection];

            if (i == 2) { // 点击上一题按钮
                if (lastGameRow == 0) {
                    return [RACSignal empty];
                }
                [self chooseGameAtIndex:[NSIndexPath indexPathForRow:(lastGameRow - 1) inSection:lastGameSection]];
            }else if (i == 0)  // 点击提示按钮
            {
                if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
                    [self getOnlyNumberWith:nil];
                }else
                {
                self.helpClickCount++;
                if (self.helpClickCount%2 == 0 && self.helpClickCount!=0) {
                    self.isShowOnlyNumber = YES;
                }else
                {
                    self.isShowOnlyNumber = NO;
                }
                [self.coverLabel removeFromSuperview];
                [self removeAllSmallCover];
                //                    [self removeAllSmallCover];
                [self getAnswerOfCheckButton:self.selectedButton];
                }
 
            }else if(i == 1) // 点击帮助按钮
            {
                if (self.limitButton.enabled == NO ) {
                    return [RACSignal empty];
                }
                [self getOnlyNumberWith:nil];
                
//                [self verificationConflict];
//                BOOL isHaveSame = NO; //是否有相同的；
//                for (SDCheckButton *checkButton in self.gameView.subviews) {
//                    if (checkButton.isError) {
//                        isHaveSame = YES;
//                        break;
//                    }
//                }
//                NSString *title = isHaveSame?@"填错了，再检查一下吧！":@"填对喽，请继续下一步吧！";
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:title delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                
//                [alert show];

            }else // 点击下一题按钮
            {
                if (lastGameRow >= askCount-1) {
                    return [RACSignal empty];
                }
                [self chooseGameAtIndex:[NSIndexPath indexPathForRow:(lastGameRow+1) inSection:lastGameSection]];
            }
            
            return [RACSignal empty];
        }];

        
    }
    [self verificationGameover];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
// 验证输入的数字也同行同列是否有冲突，小九宫格是否冲突
- (void)verificationConflict
{
    
    for (int i = 0; i < numCount; i++) {
        SDCheckButton *button = self.gameView.subviews[i];
        NSString *titleStr = button.currentTitle;
        NSInteger selectRow = i/rowCount;
        NSInteger selectColumn = i%rowCount;
        
        NSInteger sectionRow = selectRow/3; // 小九宫格组
        NSInteger sectionColumn = selectColumn/3;
        NSString *indexString = [NSString stringWithFormat:@"%ld%ld",sectionRow,sectionColumn];
        if ([titleStr isEqualToString:@"0"] || [titleStr isEqualToString:@" "]) {
            continue;
        }
        BOOL isHaveSame = NO; //是否有相同的；
        for (int j = 0; j<numCount; j++) {
            if (i == j) {
                continue;
            }
            SDCheckButton *otherButton = self.gameView.subviews[j];
            NSString *otherTitleStr = otherButton.currentTitle;
            if ([otherTitleStr isEqualToString:@"0"] || [otherTitleStr isEqualToString:@" "]) {
                continue;
            }
            NSInteger row = j/rowCount;
            NSInteger column = j%rowCount;
            NSInteger otherSectionRow = row/3;
            NSInteger otherSectionColumn = column/3;
            NSString *otherIndexString = [NSString stringWithFormat:@"%ld%ld",otherSectionRow,otherSectionColumn];

            
            // 判断同行同列， 小九宫格
            
            if (row == selectRow || column == selectColumn || [indexString isEqualToString:otherIndexString]) {
                if (otherTitleStr && [titleStr isEqualToString:otherTitleStr]) {
                    isHaveSame = YES;
                    
                }
            }
        }
        if (isHaveSame) {
            button.isError = YES;
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//            return YES;
        }else
        {
            button.isError = NO;
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            return NO;
            
        }
        
    }
    
//    return NO;
 
}

// 验证游戏是否结束完成
- (void)verificationGameover
{
    if (self.unFillCheckArray.count <= 12 &&  self.levelDetailModel.playState != LevelPlayStateSolved) {
        self.limitButton.enabled = YES;
    }else
    {
        self.limitButton.enabled = NO;
 
    }
//    if (self.unFillCheckArray.count == 0) {
    
        BOOL isGameover = YES;
        for (SDCheckButton *button in self.gameView.subviews) {
            if (button.isError  || [button.currentTitle isEqualToString:@" "]) {
                isGameover = NO;
                break;
            }
        }
        if (isGameover) {
            if (self.levelDetailModel.playState != LevelPlayStateSolved) {
//                static dispatch_once_t onceToken;
//                dispatch_once(&onceToken, ^{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"干的漂亮" message:@"恭喜您已解决所有谜团" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    
                    [alert show];
                    
//                });

                
            }
            
            self.levelDetailModel.playState = LevelPlayStateSolved;

            
            for (UIButton *button in self.gameView.subviews) {
                button.selected = NO;
                button.userInteractionEnabled = NO;
            }
            
            [self.timeLabel pause];


        }
//    }
    [self saveGameData];

}

// 保存数独游戏数据
- (void)saveGameData
{
    NSMutableArray *array = [NSMutableArray array];
    for (SDCheckButton *button in self.gameView.subviews) {
        NSString *titleStr = button.currentTitle;
        if ([titleStr isEqualToString:@" "]) {
            titleStr = @"0";
        }
        [array addObject:titleStr];
        
    }
    self.levelDetailModel.lastNumber = [array componentsJoinedByString:@""];
    NSString *lastTime = self.timeLabel.text;
    if (![lastTime isEqualToString:@"00:00:00"]) {
        self.levelDetailModel.playTime = self.timeLabel.text;

    }
    NSArray *indexArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastGame"];
    [[SDGameManager sharedSDGameManager] saveOneGameDataWithIndexPath:[NSIndexPath indexPathForRow:[indexArray.lastObject integerValue] inSection:[indexArray.firstObject integerValue]] andGameModel:self.levelDetailModel] ;
}

- (void)checkButtonDidBeginClick:(SDCheckButton *)button
{
    if (button.isOrigin) {
        self.selectedButton.selected = !self.selectedButton.selected;
        self.selectedButton = nil;
        return;
    }
    button.clickCount++;
    [self.coverLabel removeFromSuperview];
    [self removeAllSmallCover];

    if (self.selectedButton != button) {
            self.helpClickCount = 0;
            self.selectedButton.clickCount = 0;
        if (!self.selectedButton.isShowMakr) {
            [self hiddenLabelOfCheckButton:self.selectedButton];
        }
            self.selectedButton.selected = !self.selectedButton.selected;
            button.selected = !button.selected;
            self.selectedButton = (SDCheckButton *)button;
        
            
    }
    if ([button.currentTitle isEqualToString:@" "]) {
        NSInteger i = [self.gameView.subviews indexOfObject:button];
        //        NSString *titleStr = button.currentTitle;
        NSInteger selectRow = i/rowCount;
        NSInteger selectColumn = i%rowCount;
        
        NSInteger sectionRow = selectRow/3; // 小九宫格组
        NSInteger sectionColumn = selectColumn/3;
        NSString *indexString = [NSString stringWithFormat:@"%ld%ld",sectionRow,sectionColumn];

        if (button.clickCount == 2) {
            self.isShowOnlyNumber = NO;
            [self getTempErrorNumberWith:button indexString:indexString indexPath:[NSIndexPath indexPathForRow:selectRow inSection:selectColumn]];
        }else if (button.clickCount == 3)
        {
            self.isShowOnlyNumber = YES;
            [self getTempErrorNumberWith:button indexString:indexString indexPath:[NSIndexPath indexPathForRow:selectRow inSection:selectColumn]];

        }
    }
    BOOL isShowCrossView = [[NSUserDefaults standardUserDefaults] boolForKey:@"isShowCrossView"];
    if (isShowCrossView) {
        [self creatCrossCover:button];

    }

    
}
- (void)checkButtonDidEndClick:(UIButton *)button
{
    [self removeCrossCover:button];
}

- (void)creatCrossCover:(UIButton *)button
{
    [self.coverView1 removeFromSuperview];
    [self.coverView2 removeFromSuperview];
    UIView *coverView1 = [[UIView alloc] init];
    coverView1.userInteractionEnabled = NO;
    self.coverView1 = coverView1;
    [self.gameView addSubview:coverView1];
    UIView *coverView2 = [[UIView alloc] init];
    coverView1.userInteractionEnabled = NO;
    self.coverView2 = coverView2;
    [self.gameView addSubview:coverView2];
    UIColor *color = [UIColor blueColor];
    coverView1.backgroundColor = color;
    coverView2.backgroundColor = color;
    coverView1.alpha = 0.2;
    coverView2.alpha = 0.2;
    [coverView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.gameView);
        make.top.bottom.equalTo(button);
    }];
    [coverView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(button);
        make.top.bottom.equalTo(self.gameView);
    }];

}
- (void)removeCrossCover:(UIButton *)button
{
    
    [self.coverView1 removeFromSuperview];
    [self.coverView2 removeFromSuperview];

//    if([self.gameView.subviews containsObject:self.coverView1])
//    {
//        [self.coverView1 removeFromSuperview];
//        [self.coverView2 removeFromSuperview];
//    }
//
}

// 隐藏checkButton上的所有标记
- (void)hiddenLabelOfCheckButton:(SDCheckButton *)button
{
    for (int i=0; i<9; i++) {
        UILabel *label = (UILabel *)[button viewWithTag:i+1];
        label.hidden = YES;
    }

}
-(void)removeAllSmallCover
{
    for (UIView *view in self.smallCoverArray) {
        [view removeFromSuperview];
    }
    [self.smallCoverArray removeAllObjects];
}

//计算checkButton的可能数字
- (void)getAnswerOfCheckButton:(SDCheckButton *)button
{
//    for(int i = 0;i< 10; i++)
//    {
    if(button == nil)
    {
        [self getOnlyNumberWith:nil];
        return;
    }
    if (![button.currentTitle isEqualToString:@" "] && ![button.currentTitle isEqualToString:@"0"]) {
        [self getOnlyNumberWith:button];
    }else
    {
  
        if (button.isOrigin) {
            return;
        }
        NSInteger i = [self.gameView.subviews indexOfObject:button];
//        NSString *titleStr = button.currentTitle;
        NSInteger selectRow = i/rowCount;
        NSInteger selectColumn = i%rowCount;
        
        NSInteger sectionRow = selectRow/3; // 小九宫格组
        NSInteger sectionColumn = selectColumn/3;
        NSString *indexString = [NSString stringWithFormat:@"%ld%ld",sectionRow,sectionColumn];

//        [self getErrorNumberWith:button indexString:indexString indexPath:[NSIndexPath indexPathForRow:selectRow inSection:selectColumn]];
        [self getTempErrorNumberWith:button indexString:indexString indexPath:[NSIndexPath indexPathForRow:selectRow inSection:selectColumn]];
    }
}
- (void)getOnlyNumberWith:(SDCheckButton *)button
{
    for(int i = 0;i< numCount; i++)
    {
    
        SDCheckButton *currentButton  = self.gameView.subviews[i];
        if (currentButton.isOrigin || currentButton.isError) {
            continue;
        }

    //        NSString *titleStr = button.currentTitle;
        NSInteger selectRow = i/rowCount;
        NSInteger selectColumn = i%rowCount;
    
        NSInteger sectionRow = selectRow/3; // 小九宫格组
        NSInteger sectionColumn = selectColumn/3;
        NSString *indexString = [NSString stringWithFormat:@"%ld%ld",sectionRow,sectionColumn];
    
        NSMutableArray *maybeNumberArray = [NSMutableArray array];
        for (int j = 1; j < 10; j++) {
    
            NSString *maybeNumber = [NSString stringWithFormat:@"%d",j];
    
            BOOL isValid = YES;
    
            for (int k = 0; k < numCount; k++) {
                SDCheckButton *otherButton = self.gameView.subviews[k];
                NSString *otherTitleStr = otherButton.currentTitle;
                if ([otherTitleStr isEqualToString:@"0"] || [otherTitleStr isEqualToString:@" "] || (otherButton.isError && !otherButton.isOrigin)) {
                    continue;
                }
                NSInteger row = k/rowCount;
                NSInteger column = k%rowCount;
                NSInteger otherSectionRow = row/3;
                NSInteger otherSectionColumn = column/3;
                NSString *otherIndexString = [NSString stringWithFormat:@"%ld%ld",otherSectionRow,otherSectionColumn];
        
        
                // 判断同行同列， 小九宫格
                if (row == selectRow || column == selectColumn || [indexString isEqualToString:otherIndexString])
                {
                    if ([maybeNumber isEqualToString:otherTitleStr]) {
                        isValid = NO;
                        continue;
                }
        }
        
    }
    

            if (isValid == YES) {
                [maybeNumberArray addObject:@(j)];
            }
        }
        if(maybeNumberArray.count == 1)
        {
                UILabel *coverLabel = [[UILabel alloc] init];
                [self.smallCoverArray addObject:coverLabel];
                //            self.coverLabel = coverLabel;
                coverLabel.userInteractionEnabled = NO;
                [currentButton addSubview:coverLabel];
//                coverLabel.text = [NSString stringWithFormat:@"%@", maybeNumberArray.firstObject];
                coverLabel.textAlignment = NSTextAlignmentCenter;
                coverLabel.backgroundColor = mRGBToColor(0x98F5FF);
                coverLabel.alpha  =1;
                [coverLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.left.bottom.right.equalTo(currentButton);
                }];
                [coverLabel.layer addAnimation:[self opacityForever_Animation:1 fromValue:@(1)] forKey:nil];

        }
    
    
    }
    [self verificationGameover];

}

- (void)getErrorNumberWith:(SDCheckButton *)button indexString:(NSString *)indexString indexPath:(NSIndexPath *)indexPath
{
    //判断可能有效数字
    NSMutableArray *errorNumberArray = [NSMutableArray array];
    NSMutableArray *numberArray = [NSMutableArray array];
    
    [self removeAllSmallCover];
    [numberArray addObjectsFromArray:@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"]];
    NSInteger selectRow = indexPath.row;
    NSInteger selectColumn = indexPath.section;
    for (int k = 0; k < numCount; k++) {
        SDCheckButton *otherButton = self.gameView.subviews[k];
        NSString *otherTitleStr = otherButton.currentTitle;
        if ([otherTitleStr isEqualToString:@"0"] || [otherTitleStr isEqualToString:@" "] || (otherButton.isError&&!otherButton.isOrigin)) {
            continue;
        }

        NSInteger row = k/rowCount;
        NSInteger column = k%rowCount;
        NSInteger otherSectionRow = row/3;
        NSInteger otherSectionColumn = column/3;
        NSString *otherIndexString = [NSString stringWithFormat:@"%ld%ld",otherSectionRow,otherSectionColumn];
        
        
        // 判断同行同列， 小九宫格
        if (row == selectRow || column == selectColumn || [indexString isEqualToString:otherIndexString]) {
            if ([numberArray containsObject:otherTitleStr]) {
                [numberArray removeObject:otherTitleStr];
                [errorNumberArray addObject:otherButton];
            }
        }
        
    }
  
    if(!self.isShowOnlyNumber)
    {
        button.isShowMakr = NO;
        for (SDCheckButton *button in errorNumberArray) {
            UIView *coverView = [[UIView alloc] init];
            coverView.userInteractionEnabled = NO;
            [self.smallCoverArray addObject:coverView];
            [button addSubview:coverView];
            coverView.backgroundColor = mRGBToColor(0x98F5FF);
            [coverView.layer addAnimation:[self opacityForever_Animation:1 fromValue:@(1)] forKey:nil];
            [coverView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.bottom.right.equalTo(button);
            }];
            //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //            [coverView removeFromSuperview];
            //        });
            
        }
        for (NSString *str in numberArray) {
            UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
            label.hidden = NO;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (!button.isShowMakr) {
                    [self hiddenLabelOfCheckButton:button];

                }
            });
            
        }
        

    }else
    {
        button.isShowMakr = YES;
        if (numberArray.count == 1) {
            button.isFill = YES;
            [button setTitle:[NSString stringWithFormat:@"%@",numberArray.firstObject] forState:UIControlStateNormal];
        }else
        {
            for (NSString *str in numberArray) {
            UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
            label.hidden = NO;
            }
        }
        

    }


}

- (void)getTempErrorNumberWith:(SDCheckButton *)button indexString:(NSString *)indexString indexPath:(NSIndexPath *)indexPath
{
    [self hiddenLabelOfCheckButton:button];
    //判断可能有效数字
    NSMutableArray *errorNumberArray = [NSMutableArray array];
    NSMutableArray *numberArray = [NSMutableArray array];
    NSInteger buttonIndex = [self.gameView.subviews indexOfObject:button];

    [self removeAllSmallCover];
    [numberArray addObjectsFromArray:@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"]];
    NSInteger selectRow = indexPath.row;
    NSInteger selectColumn = indexPath.section;
    for (int k = 0; k < numCount; k++) {
        SDCheckButton *otherButton = self.gameView.subviews[k];
        NSString *otherTitleStr = otherButton.currentTitle;
        if ([otherTitleStr isEqualToString:@"0"] || [otherTitleStr isEqualToString:@" "] || (otherButton.isError&&!otherButton.isOrigin)) {
            continue;
        }
        
        NSInteger row = k/rowCount;
        NSInteger column = k%rowCount;
        NSInteger otherSectionRow = row/3;
        NSInteger otherSectionColumn = column/3;
        NSString *otherIndexString = [NSString stringWithFormat:@"%ld%ld",otherSectionRow,otherSectionColumn];
        
        
        // 判断同行同列， 小九宫格
        if (row == selectRow || column == selectColumn || [indexString isEqualToString:otherIndexString]) {
            if ([numberArray containsObject:otherTitleStr]) {
                [numberArray removeObject:otherTitleStr];
                [errorNumberArray addObject:otherButton];
            }
        }
        
    }
    if (numberArray.count == 1) {
        if(!self.isShowOnlyNumber)
        {
            
            button.isShowMakr = NO;
            for (SDCheckButton *button in errorNumberArray) {
                //            if (button.isFill) {
                UIView *coverView = [[UIView alloc] init];
                coverView.userInteractionEnabled = NO;
                [self.smallCoverArray addObject:coverView];
                [button addSubview:coverView];
                coverView.backgroundColor = mRGBToColor(0x98F5FF);
                coverView.alpha = 0.2;
                [coverView.layer addAnimation:[self hiddenForever_Animation:1 fromValue:@(1)] forKey:nil];
                [coverView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.left.bottom.right.equalTo(button);
                }];
                
                if (!button.isFill) {
                    [self hiddenLabelOfCheckButton:button];
                    NSInteger index = [self.gameView.subviews indexOfObject:button];
                    NSArray *maybeNumberArray = [self getMayBeNumArray:index];
                    for (NSString *str in maybeNumberArray) {
                        UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
                        label.hidden = NO;
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            if (!button.isShowMakr) {
                                [self hiddenLabelOfCheckButton:button];
                                
                            }
                        });
                        
                    }
                    
                }
                
            }
            for (NSString *str in numberArray) {
                UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
                label.hidden = NO;
            }
            
            
        }else
        {
            button.isShowMakr = YES;
            if (numberArray.count == 1) {
                button.isFill = YES;
                [button setTitle:[NSString stringWithFormat:@"%@",numberArray.firstObject] forState:UIControlStateNormal];
                if ([self.unFillCheckArray containsObject:button]) {
                    [self.unFillCheckArray removeObject:button];
                }
                [self verificationGameover];
            }else
            {
                for (NSString *str in numberArray) {
                    UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
                    label.hidden = NO;
                }
            }
            
            
        }
        return;

    }
    { // 判断同行区域
    NSArray *sameRowArray = [self getSameRowIndex:buttonIndex];
    NSMutableArray *tempArray = [NSMutableArray array];
    for (int n = 0; n < sameRowArray.count; n++) {
        NSNumber *number = sameRowArray[n];
        NSArray *mayBeNumArray = [self getMayBeNumArray:[number integerValue]];
        [tempArray addObject:mayBeNumArray];
    }
    
    for (int m = 0; m < tempArray.count; m++) {
        NSArray *mayBeNumArray = tempArray[m];
        if (mayBeNumArray.count == 1) {
            NSString *titleStr = [NSString stringWithFormat:@"%@",mayBeNumArray.firstObject];
            if ([numberArray containsObject:titleStr]) {
                [numberArray removeObject:titleStr];
                NSInteger index = [sameRowArray[m] integerValue];
                [errorNumberArray addObject:self.gameView.subviews[index]];
            }
        }
    }
    }
    
    {  // 判断同列区域
        NSArray *sameColumnArray = [self getSameColumIndex:buttonIndex];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int n = 0; n < sameColumnArray.count; n++) {
            NSNumber *number = sameColumnArray[n];
            NSArray *mayBeNumArray = [self getMayBeNumArray:[number integerValue]];
            [tempArray addObject:mayBeNumArray];
        }
        
        for (int m = 0; m < tempArray.count; m++) {
            NSArray *mayBeNumArray = tempArray[m];
            if (mayBeNumArray.count == 1) {
                NSString *titleStr = [NSString stringWithFormat:@"%@",mayBeNumArray.firstObject];
                if ([numberArray containsObject:titleStr]) {
                    [numberArray removeObject:titleStr];
                    NSInteger index = [sameColumnArray[m] integerValue];
                    [errorNumberArray addObject:self.gameView.subviews[index]];
                }
            }
        }

    }
    { // 判断同九宫格区域
        NSArray *sameCellArray = [self getSameCellIndex:buttonIndex];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int n = 0; n < sameCellArray.count; n++) {
            NSNumber *number = sameCellArray[n];
            NSArray *mayBeNumArray = [self getMayBeNumArray:[number integerValue]];
            [tempArray addObject:mayBeNumArray];
        }
        
        for (int m = 0; m < tempArray.count; m++) {
            NSArray *mayBeNumArray = tempArray[m];
            if (mayBeNumArray.count == 1) {
                NSString *titleStr = [NSString stringWithFormat:@"%@",mayBeNumArray.firstObject];
//                button.isFill == YES;
                if ([numberArray containsObject:titleStr]) {
                    [numberArray removeObject:titleStr];
                    NSInteger index = [sameCellArray[m] integerValue];
                    [errorNumberArray addObject:self.gameView.subviews[index]];
                }
            }
        }

    }
    if(!self.isShowOnlyNumber)
    {
        
        button.isShowMakr = NO;
        for (SDCheckButton *button in errorNumberArray) {
//            if (button.isFill) {
                UIView *coverView = [[UIView alloc] init];
                coverView.userInteractionEnabled = NO;
                [self.smallCoverArray addObject:coverView];
                [button addSubview:coverView];
                coverView.backgroundColor = mRGBToColor(0x98F5FF);
                coverView.alpha = 0.2;
                [coverView.layer addAnimation:[self hiddenForever_Animation:1 fromValue:@(1)] forKey:nil];
                [coverView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.left.bottom.right.equalTo(button);
                }];

            if (!button.isFill) {
                [self hiddenLabelOfCheckButton:button];
                NSInteger index = [self.gameView.subviews indexOfObject:button];
                NSArray *maybeNumberArray = [self getMayBeNumArray:index];
                for (NSString *str in maybeNumberArray) {
                    UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
                    label.hidden = NO;
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        if (!button.isShowMakr) {
                            [self hiddenLabelOfCheckButton:button];
                            
                        }
                    });
                    
                }

            }
            
        }
        for (NSString *str in numberArray) {
            UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
            label.hidden = NO;
            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                if (!button.isShowMakr) {
//                    [self hiddenLabelOfCheckButton:button];
//                    
//                }
//            });
            
        }
        
        
    }else
    {
        button.isShowMakr = YES;
        if (numberArray.count == 1) {
            button.isFill = YES;
            [button setTitle:[NSString stringWithFormat:@"%@",numberArray.firstObject] forState:UIControlStateNormal];
            if ([self.unFillCheckArray containsObject:button]) {
                [self.unFillCheckArray removeObject:button];
            }
            [self verificationGameover];
        }else
        {
            for (NSString *str in numberArray) {
                UILabel *label = (UILabel *)[button viewWithTag:[str integerValue]];
                label.hidden = NO;
            }
        }
        
        
    }

    
    
    
}


-(CABasicAnimation *)opacityForever_Animation:(float)time fromValue:(NSNumber *)fromValue

{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];//必须写opacity才行。
    
    animation.fromValue = @(0);
    
    animation.toValue = fromValue;//[NSNumber numberWithFloat:0.0f];//这是透明度。
    
    animation.autoreverses = YES;
    
    animation.duration = time;
    
    animation.repeatCount = MAXFLOAT;
    
    animation.removedOnCompletion = YES;
    
    animation.fillMode = kCAFillModeForwards;
    
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];///没有的话是均匀的动画。
    
    return animation;
    
}
-(CABasicAnimation *)hiddenForever_Animation:(float)time fromValue:(NSNumber *)fromValue

{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"hidden"];//必须写opacity才行。
    
    animation.fromValue = @(0);
    
    animation.toValue = fromValue;//[NSNumber numberWithFloat:0.0f];//这是透明度。
    
    animation.autoreverses = YES;
    
    animation.duration = time;
    
    animation.repeatCount = MAXFLOAT;
    
    animation.removedOnCompletion = YES;
    
    animation.fillMode = kCAFillModeForwards;
    
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];///没有的话是均匀的动画。
    
    return animation;
    
}


- (NSArray *)getSameRowIndex:(NSInteger)index
{
    NSMutableArray *sameRowIndexArray = [NSMutableArray array];
    NSInteger selectRow = index/rowCount;
    for (int k = 0; k < numCount; k++) {
        if(k == index)
        {
            continue;
        }
        SDCheckButton *otherButton = self.gameView.subviews[k];
        if (otherButton.isOrigin ) {
            continue;
        }
        
        NSInteger row = k/rowCount;
        if (row == selectRow ) {
            [sameRowIndexArray addObject:@(k)];
        }
        
    }
    return sameRowIndexArray;
}
- (NSArray *)getSameColumIndex:(NSInteger)index
{
    NSMutableArray *sameColumnIndexArray = [NSMutableArray array];
    NSInteger selectColumn = index%rowCount;
    for (int k = 0; k < numCount; k++) {
        if(k == index)
        {
            continue;
        }
        SDCheckButton *otherButton = self.gameView.subviews[k];
        if (otherButton.isOrigin ) {
            continue;
        }
        
        NSInteger row = k%rowCount;
        if (row == selectColumn ) {
            [sameColumnIndexArray addObject:@(k)];
        }
        
    }
    return sameColumnIndexArray;
}

- (NSArray *)getSameCellIndex:(NSInteger)index
{
    NSMutableArray *sameCellIndexArray = [NSMutableArray array];
    NSInteger selectRow = index/rowCount;
    NSInteger selectColumn =index%rowCount;
    
    NSInteger sectionRow = selectRow/3; // 小九宫格组
    NSInteger sectionColumn = selectColumn/3;
    NSString *indexString = [NSString stringWithFormat:@"%ld%ld",sectionRow,sectionColumn];

    for (int k = 0; k < numCount; k++) {
        if(k == index)
        {
            continue;
        }
        SDCheckButton *otherButton = self.gameView.subviews[k];
        if (otherButton.isOrigin ) {
            continue;
        }
        NSInteger row = k/rowCount;
        NSInteger column = k%rowCount;
        NSInteger otherSectionRow = row/3;
        NSInteger otherSectionColumn = column/3;
        NSString *otherIndexString = [NSString stringWithFormat:@"%ld%ld",otherSectionRow,otherSectionColumn];
        
        if ([indexString isEqualToString:otherIndexString] ) {
            [sameCellIndexArray addObject:@(k)];
        }
        
    }
    return sameCellIndexArray;
}


- (NSArray *)getMayBeNumArray:(NSInteger)index
{
    NSMutableArray *numberArray = [NSMutableArray array];
    
    [numberArray addObjectsFromArray:@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"]];
    NSInteger selectRow = index/rowCount;
    NSInteger selectColumn = index%rowCount;
    NSInteger sectionRow = selectRow/3;
    NSInteger sectionColumn = selectColumn/3;
    NSString *indexString = [NSString stringWithFormat:@"%ld%ld",sectionRow,sectionColumn];

    for (int k = 0; k < numCount; k++) {
        SDCheckButton *otherButton = self.gameView.subviews[k];
        NSString *otherTitleStr = otherButton.currentTitle;
        if ([otherTitleStr isEqualToString:@"0"] || [otherTitleStr isEqualToString:@" "] || (otherButton.isError&&!otherButton.isOrigin)) {
            continue;
        }
        
        NSInteger row = k/rowCount;
        NSInteger column = k%rowCount;
        NSInteger otherSectionRow = row/3;
        NSInteger otherSectionColumn = column/3;
        NSString *otherIndexString = [NSString stringWithFormat:@"%ld%ld",otherSectionRow,otherSectionColumn];
        
        
        // 判断同行同列， 小九宫格
        if (row == selectRow || column == selectColumn || [indexString isEqualToString:otherIndexString]) {
            if ([numberArray containsObject:otherTitleStr]) {
                [numberArray removeObject:otherTitleStr];
            }
        }
        
    }
    
    return numberArray;
}
@end
